package nsqframe

import (
	"encoding/json"
	"io/ioutil"
	"os"
)

const (
	CONSUMER_CACHE_LEN = 1024
	PRODUCER_CACHE_LEN = 1024
)

type NFNsqConfig struct {
	Server string `json:"server"`
	Topic  string `json:"topic"`
	Chan   string `json:"chan"`
}

//consumer config
type NFCConfig struct {
	Concurrent int          `json:"concurrent"`
	CacheLen   int          `json:"cachelen"`
	Nsq        *NFNsqConfig `json:"nsq"`
}

//producer config
type NFPConfig struct {
	Concurrent int          `json:"concurrent"`
	CacheLen   int          `json:"cachelen"`
	Nsq        *NFNsqConfig `json:"nsq"`
}

type NFConfig struct {
	Consumer *NFCConfig `json:"consumer"`
	Producer *NFPConfig `json:"producer"`
}

type NFDBConfig struct {
	NFConfig

	db string
}

func (p *NFCConfig) check() error {
	if p.CacheLen <= 0 {
		p.CacheLen = CONSUMER_CACHE_LEN
	}

	if p.Concurrent <= 0 {
		p.Concurrent = 1
	}

	return nil
}

func (p *NFPConfig) check() error {
	if p.CacheLen <= 0 {
		p.CacheLen = PRODUCER_CACHE_LEN
	}

	if p.Concurrent <= 0 {
		p.Concurrent = 1
	}

	return nil
}

func ReadConfig(fn string, cfg interface{}) error {
	f, err := os.Open(fn)
	if err != nil {
		return err
	}
	defer f.Close()

	data, err := ioutil.ReadAll(f)
	if err != nil {
		return err
	}

	err = json.Unmarshal(data, cfg)
	if err != nil {
		return err
	}

	return nil
}
